##############################################################################
# 
#  Author: Neal Walters 
#    Date: 01/16/2011 
# Purpose: Read export PhatNotes.CSV and convert to Evernote.ENEX 
#          to be able to migrate notes from PhatNotes to Evernote. 
#
##############################################################################
import csv 
import sys 
import os
#import os.path 
from datetime import datetime

printOn = False 

def formatDateTimetoXML(dateTimeIn): 
  try: 
     d = datetime.strptime(dateTimeIn, '%m/%d/%Y %H:%M:%S %p')
     day_string = d.strftime('%Y%m%dT%H%M%S')
     return day_string 
  except:
     #second chance, editing file in Excel may drop/round seconds 
     try: 
        d = datetime.strptime(dateTimeIn, '%m/%d/%Y %H:%M')
        day_string = d.strftime('%Y%m%dT%H%M%S')
        return day_string 
     except: 
        print "DateTimeConversion Error: dateTimeIn=" + dateTimeIn 
	sys.exit(0)
        #pause = raw_input(">")
        #return dateTimeIn 
     
def cleanTitle(titleIn): 
   #change any illegal characters here to some other character or nothing 
   titleOut = titleIn; 
   #titleOut = titleOut.replace("=","")
   titleOut = titleOut.replace("&","&amp;")
   return titleOut 

def cleanNote(noteIn): 
   #change any desired characters 
   noteOut = noteIn; 
   noteOut = noteOut.replace("&","&amp;")
   noteOut = noteOut.replace("<","&lt;")
   noteOut = noteOut.replace(">","&gt;")
   noteOut = noteOut.replace('"',"&quot;")
   noteOut = noteOut.replace("'","&apos;")
   #this has to be done after the above to the less-than greater-than doesn't get replaced again 
   noteOut = noteOut.replace("\r\n","<br />\n")
   return noteOut 


# Allow for easy defaults when testing 
#  NOTE: The first arg is always the Python filename 

print "Number of args = " + str(len(sys.argv))
for i, arg in enumerate(sys.argv): 
   print str(i) + ":" + arg 

if len(sys.argv) < 1:
   database = "PhatNotesConverterDemo" 
else: 
   database = sys.argv[1]

if len(sys.argv) < 2:
   #inputCSVFilename = "c:\PhatNotes\Sample.csv" 
   inputCSVFilename = "Sample.csv" 
else: 
   inputCSVFilename = sys.argv[2] 

if len(sys.argv) < 3:
   YNPhatCategory = "Y" 
else: 
   YNPhatCategory = sys.argv[3]

if len(sys.argv) < 4:
   YNPhatColor    = "Y" 
else: 
   YNPhatColor    = sys.argv[4]

if len(sys.argv) < 5:
   YNPhatPriority = "Y" 
else: 
   YNPhatPriority = sys.argv[5]

basename, extension = os.path.splitext(inputCSVFilename)
outFilename = basename + ".ENEX"  

# tricks for finding database name in filename \
tempDatabase = database 
if database == "$BASEFILENAME":
   database = basename #(the base of the Phatnotes .csv filename) 
if database == "$AFTERLAST_":
   parts = basename.split("_")
   if len(parts) > 0: 
      database = parts[-1] # the last item in the list (after the split) 
if database == "$BEFOREFIRST_":
   parts = basename.split("_") 
   if len(parts) > 0: 
     database = parts[0] # the first item in the list (after the split) 


print "==========================================="
print "PARMS:" 
print "  1) database=" + database 
print "  2) inputCSVFilename=" + inputCSVFilename 
print "  3) YNPhatCategory=" + YNPhatCategory 
print "  4) YNPhatColor=" + YNPhatColor 
print "  5) YNPhatPriority=" + YNPhatPriority 
print "==========================================="
print " "



if not os.path.isfile(inputCSVFilename):
  print "Input CSV Filename: '" + inputCSVFilename + "' does not exist" 
  sys.exit(0)

noteTemplateFilename = "EverNote_Template_Note.xml"

outFile = open(outFilename,"w") 

noteTemplateFile = open(noteTemplateFilename,"r")
noteTemplateText = noteTemplateFile.read()  
noteTemplateFile.close()

headerFilename = "EverNote_Template_Header.xml"
footerFilename = "EverNote_Template_Footer.xml"
headerContents = open(headerFilename).read() 
footerContents = open(footerFilename).read() 

outFile.write(headerContents) 


#fix null characters 
#some CSV files have two nulls on the end? 
fileContents = open(inputCSVFilename).read().replace("\0", "")
inFile = open(inputCSVFilename,"w")
inFile.write(fileContents)
inFile.close() 



columnName = ['subject', 'created', 'modified', 'note', 'category', 'authored', 'color', 'priority', 'future', 'future2', 'future3'] 
csvReader = csv.reader(open(inputCSVFilename, 'rb'), delimiter=',', quotechar='"')

#for (rownum, row) in enumerate(csvReader):  this syntax caused "Error: liens contains NULL byte on last row 

rownum = 0 
for row in csvReader:
    if printOn: 
       print str(rownum) + ": row=" + str(row) 
    # 0=subject, 1=created, 2=modified 3=note 4=category 5=authored, 6=color, 7=Priority 
    (subject, created, modified, note, category, authored, color, priority) = row 

    if rownum > 1 or subject != "Subject": 
        rownum = rownum + 1 
	#don't write out an EverNote for the CSV headers 
        if printOn: 
          print "subject=" + subject 
  	  print "created=" + created 
	  print "modified=" + modified 
	  print "note=" + note 
	  print "category=" + category 
	  print "authored=" + authored 
	  print "color=" + color 
	  print "priority=" + priority 

        #for (i,column) in enumerate(row):
        #  #print "i=" + str(i) 
        #  print str(i) + ":" + columnName[i] + ":" + column 
	#  if i==0: subject=column 
	#  if i==1: created=column 
        #pause = raw_input(">")

  	noteText = noteTemplateText.replace("&title",cleanTitle(subject)) 
	noteText = noteText.replace("&notetext",cleanNote(note)) 
	noteText = noteText.replace("&created",formatDateTimetoXML(created))
	noteText = noteText.replace("&updated",formatDateTimetoXML(modified)) 

	# there may or may not be a category 
	if category > " " and YNPhatCategory == "Y":
	   noteText = noteText.replace("&tag1","PhatNotesCategory=" + category)
	else: 
	   noteText = noteText.replace("<tag>&tag1</tag>","") 

	# there may or may not be a color  
	if color > " " and YNPhatColor == "Y":
	   noteText = noteText.replace("&tag2","PhatNotesColor="+color)
	else: 
	   noteText = noteText.replace("<tag>&tag2</tag>","") 

	# there may or may not be a priority  
	if priority > " " and YNPhatPriority == "Y":
	   noteText = noteText.replace("&tag3","PhatNotesPriority="+priority
	   )
	else: 
	   noteText = noteText.replace("<tag>&tag3</tag>","") 

	# there must be a database-name 
	if database > " ":
	   noteText = noteText.replace("&tag4","PhatNotesDatabase="+database)
	else: 
	   noteText = noteText.replace("<tag>&tag4</tag>","") 

	outFile.write("\r\n" + noteText)

outFile.write("\r\n" + footerContents) 
outFile.close() 

print "Created output file: " + outFilename + " with " + str(rownum) + " notes." 
